import React, { PureComponent } from 'react';
import Exception from '../Exception';
import styles from './index.module.scss';

interface IState {
  hasError: boolean;
  error: Error;
  info: object;
}

interface IProp {
  type: string;
  children: React.ReactNode;
}

/**
 * 应用错误便捷
 */
export default class ErrorBoundary extends PureComponent<IProp, IState> {
  static defaultProps = {
    type: 'route'
  };
  constructor(props: IProp) {
    super(props);
    this.state = {
      hasError: false,
      error: new Error(),
      info: {},
    };
  }

  public componentDidCatch(error: Error, info: object) {
    this.setState({ hasError: true, error, info });
  }

  public render() {
    if (this.state.hasError) {
      if(this.props.type === 'chart'){
        return <div className={styles.chartError} />;
      }
      return (
        <Exception type={500} />
      );
    }

    return this.props.children;
  }
}
